<template>
    <div class="transaction-result">
        <overlay v-if="showMaskLayer" />
        <div class="transaction-wrap" v-else-if="detailOrderData && !showMaskLayer">
            <div class="steps">
                <van-steps :active="active">
                    <van-step v-for="(item, index) in status" :key="index">
                        {{ item }}
                    </van-step>
                </van-steps>
            </div>
            <div class="maintain">
                <div class="order-price">
                    <div class="bigNumber">
                        <span class="num" v-text="detailOrderData.orderPrice"></span>
                        <span class="unit">&nbsp;{{$t('dollar')}}</span>
                        <span class="arrow">&nbsp;<van-icon name="arrow"/></span>
                    </div>
                </div>
            </div>
            <div class="order-info">
                <div class="info-header">
                    <span v-text="detailOrderData.orderAuthor"></span>
                    <span v-text="detailOrderData.orderPhone"></span>
                </div>
                <div class="info-footer" v-text="detailOrderData.orderAddress"></div>
            </div>
            <div class="order-describe">
                <div class="describe-center">
                    <div class="describe-img">
                        <img :src="detailOrderData.orderPicture[0]" alt="" />
                    </div>
                    <div class="describe-text">
                        <span v-text="detailOrderData.orderContent"></span>
                    </div>
                </div>
            </div>
            <div class="transaction-record">
                <div class="line">
                    <span>{{ $t("orders.nicknameOfIssue") }}</span>
                    <span ref="releaseId"></span>
                </div>
                <div class="line">
                    <span>{{ $t("orders.nicknameOfTake") }}</span>
                    <span ref="errandsId"></span>
                </div>
                <div class="line">
                    <span>{{ $t("orders.orderNumber") }}</span>
                    <span v-text="detailOrderData._id"></span>
                </div>
                <div class="line">
                    <span>{{ $t("orders.transactionTime") }}</span>
                    <span>{{requestTransactionTime}}</span>
                </div>
            </div>
            <div class="button-group">
                <van-button round type="info" @click="chatting">
                    {{ $t("chat") }}</van-button
                >
                <van-button
                        round
                        type="warning"
                        v-if="showDefaultButton"
                        @click="confirmPayment"
                        :disabled="active === 3"
                >
                    {{ $t("confirmPay") }}
                </van-button>
                <van-button
                        round
                        type="primary"
                        v-else
                        @click="confirmDelivery"
                        :disabled="active >= 2"
                >
                    {{ $t("confirmFinish") }}
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { Step, Steps, Icon, Button } from 'vant';
import overlay from 'components/content/overlay/overlay.vue';
import { mapState, mapMutations } from 'vuex';
import 'vant/lib/step/style/less';
import 'vant/lib/steps/style/less';

export default {
    name: 'transaction-details',
    data () {
        return {
            active: 0,
            showDefaultButton: false,
            detailOrderData: undefined,
            issueUser: undefined,
            applyUser: undefined,
            requestTransactionTime: '等待交易',
            status: ['等待接单', '正在跑腿', '完成跑腿', '交易成功']
        };
    },
    components: {
        overlay,
        [Step.name]: Step,
        [Steps.name]: Steps,
        [Icon.name]: Icon,
        [Button.name]: Button
    },
    created () {
        if (!this.$route.params.id) return;
        this.resetStatus({ state: 'showMaskLayer', status: true });
        this.$api.orderApi.detail(this.$route.params.id).then(res => {
            if (res.code === 2009) {
                this.showDefaultButton = res.data.orderByCreateID === this.$store.state.userInfo._id;
                const promise = new Promise((resolve, reject) => {
                    const requestIssue = {
                        url: '/api/v1/profile/',
                        method: 'get',
                        params: {
                            id: res.data.orderByCreateID
                        }
                    };
                    const requestApply = {
                        url: '/api/v1/apply/returnUser',
                        method: 'get',
                        params: {
                            id: res.data._id
                        }
                    };
                    this.$api.otherApi
                        .axiosAll(requestIssue, requestApply)
                        .then(result => {
                            this.active = res.data.orderStatus - 1;
                            this.detailOrderData = res.data;
                            // eslint-disable-next-line prefer-promise-reject-errors
                            result.length ? resolve(result, res) : reject();
                        })
                        .catch();
                });
                promise
                    .then(result => {
                        this.issueUser = result[0].data;
                        this.applyUser = result[1].data;
                        this.$nextTick(() => {
                            this.$refs.releaseId.textContent = this.issueUser.nickname;
                            this.$refs.errandsId.textContent = this.applyUser.nickname;
                        });
                    })
                    .catch(() => {
                        this.$util.failToast('获取的用户信息为空');
                    });
            } else {
                this.$util.failToast('获取接单信息失败');
                setTimeout(() => {
                    this.$router.go(-1);
                }, 1500);
            }
        }).then(() => {
            this.resetStatus({ state: 'showMaskLayer', status: false });
        });
    },
    watch: {
        active: function (value) {
            if (value === 3) {
                this.$api.billsApi
                    .findTransactioTime({ id: this.detailOrderData._id })
                    .then(data => {
                        this.requestTransactionTime = this.$options.filters.dateformat(data);
                    });
            }
        }
    },
    computed: {
        ...mapState(['showMaskLayer'])
    },
    methods: {
        confirmDelivery () {
            this.$dialog
                .confirm({
                    title: this.$t('tips'),
                    message: this.$t('orderFinish'),
                    confirmButtonText: this.$t('yesOfFinish')
                })
                .then(() => {
                    const params = {
                        _id: this.detailOrderData._id,
                        isOrderFinished: true,
                        orderStatus: 3
                    };
                    this.$api.orderApi
                        .update(params)
                        .then(result => {
                            if (result.code === 2002) {
                                this.$api.orderApi
                                    .detail(this.detailOrderData._id)
                                    .then(res => {
                                        this.active = res.data.orderStatus - 1;
                                        this.$util.successToast(this.$t('orders.waitPay'));
                                    });
                            } else {
                                this.$util.failToast(result.message);
                            }
                        })
                        .catch();
                })
                .catch(() => {
                    console.info('user click cancel');
                });
        },
        confirmPayment () {
            this.$dialog
                .confirm({
                    title: this.$t('tips'),
                    message: this.$t('dialog.payForOrder'),
                    confirmButtonText: this.$t('confirmPay')
                })
                .then(() => {
                    this.$util.loadingToast();
                    this.$api.orderApi.detail(this.detailOrderData._id).then(result => {
                        if (result.data.isOrderFinished && result.data.isOrderTaked) {
                            const pay = this.$store.state.userInfo.balance;
                            if (pay >= this.detailOrderData.orderPrice) {
                                this.$api.billsApi
                                    .createBill({
                                        transactionMoney: this.detailOrderData.orderPrice,
                                        transActionType: '转账',
                                        users_id: [localStorage.getItem('id'), this.applyUser._id],
                                        orderType: this.detailOrderData._id
                                    })
                                    .then(result => {
                                        if (result) {
                                            const params = {
                                                _id: this.detailOrderData._id,
                                                orderStatus: 4
                                            };
                                            this.$api.orderApi
                                                .update(params)
                                                .then(result => {
                                                    if (result.code === 2002) {
                                                        this.$util.successToast(this.$t('orders.transactionSuccessful'));
                                                        this.active = 3;
                                                    }
                                                })
                                                .catch();
                                        } else {
                                            this.$util.failToast(this.$t('orders.transactionFailed'));
                                        }
                                    })
                                    .catch(err => {
                                        throw err;
                                    });
                            } else {
                                this.$util.failToast('您持有的金额不足以支付！请充值');
                            }
                        } else {
                            this.$util.failToast(this.$t('orders.notFinish'));
                        }
                    });
                })
                .catch(() => {
                    console.info('user click cancel');
                });
        },
        chatting () {
            const chatId = this.showDefaultButton
                ? this.applyUser._id
                : this.issueUser._id;
            this.$router.push({
                name: 'msg-detail',
                params: {
                    chatId,
                    orderId: this.detailOrderData._id
                }
            });
        },
        ...mapMutations(['resetStatus'])
    }
};
</script>

<style scoped lang="less" src="./less/transaction-detail.less"></style>
